#ifndef KUAISHOU_H
#define KUAISHOU_H
#include "libs/core/model/modeltype.h"

// 压缩Script Source Code
// const auto code = DouYin::webEntry().script.source_code;
// const auto ba = qCompress(code.toUtf8());
// const auto ba2 = ba.toHex();
// qDebug() << QString::fromLatin1(ba2);

class KuaiShou
{
public:
    static yc::LiveWebEntry webEntry()
    {
        return yc::LiveWebEntry { yc::KUAISHOW_PLATFORM_TYPE,
                                  QString("KuaiShou"),
                                  QString("https://live.kuaishou.com/u/%1"),
                                  QString("https://live.kuaishou.com/profile/%1"),
                                  yc::ANDROID_USER_AGENT_TYPE,
                                  yc::WebScript { 0, R"((function (objectName, interval) {
    // 只需要处理'livev.m.chenzhongtech.com'域名
    if (window.location.href.indexOf('livev.m.chenzhongtech.com') < 0) {
        return;
    }

    const METHOD_SET_LIVE_INFO = 'setLiveInfo';
    const METHOD_SET_LIVE_STATUS = 'setLiveStatus';
    const METHOD_SET_CAPTCHA = 'setCaptcha';

    // C++方法
    const MethodNames = {
        setLiveInfo: `${objectName}.${METHOD_SET_LIVE_INFO}`,
        setLiveStatus: `${objectName}.${METHOD_SET_LIVE_STATUS}`,
        setCaptcha: `${objectName}.${METHOD_SET_CAPTCHA}`
    };

    // 定义命名空间
    window.YCLiveUtils = window.YCLiveUtils || {};

    window.YCLiveUtils.convertChineseNumber = function(str) {
        const TEN_THOUSAND_CHAR = '\u4e07'; // 万的Unicode编码
        // 去掉空白字符
        str = str.trim();

        // 检查是否包含"万"
        if (str.includes(TEN_THOUSAND_CHAR)) {
            // 将字符串中的"万"替换为空字符串，并将结果转换为浮点数
            let num = parseFloat(str.replace(TEN_THOUSAND_CHAR, ''));

            // 乘以10000来得到实际的数值
            return num * 10000;
        } else {
            // 如果没有"万"，直接转换为数字
            return parseFloat(str);
        }
    }

    window.YCLiveUtils.safeGet = function (obj, path, defaultValue = null) {
        return path.split('.').reduce((acc, key) => acc && key in acc ? acc[key] : defaultValue, obj);
    };

    window.YCLiveUtils.isNumber = function (value) {
        return typeof value === 'number' && !isNaN(value);
    };

    window.YCLiveUtils.sortByBitrate = function (representations) {
        if (!Array.isArray(representations)) return [];
        const validRepresentations = representations.filter(rep => YCLiveUtils.isNumber(rep.bitrate));
        return validRepresentations.sort((a, b) => b.bitrate - a.bitrate);
    };

    window.YCLiveUtils.sortByLevel = function (playUrls) {
        if (!Array.isArray(playUrls)) return [];
        const validPlayUrls = playUrls.filter(url => YCLiveUtils.isNumber(url.level));
        return validPlayUrls.sort((a, b) => b.level - a.level);
    };

    window.YCLiveUtils.extractUrlFromRepresentation = function (representation, index, defaultVal = '') {
        if (representation?.[index]?.url) {
            return representation[index].url;
        }
        return defaultVal;
    };

    window.YCLiveUtils.transformSourceToTarget = function (source) {
        // 验证源对象有效性
        if (!source || typeof source !== 'object') {
            console.error('Invalid source object');
            return null;
        }

        const liveStream = window.YCLiveUtils.safeGet(source, 'liveStream', {});
        const user = window.YCLiveUtils.safeGet(liveStream, 'user', {});
        const user_id = window.YCLiveUtils.safeGet(user, 'user_id', 0);
        if (!user_id || user_id === 0) {
            user_id = window.YCLiveUtils.safeGet(liveStream, 'userEid', '')
        }
        const user_id_str = user_id && user_id.toString ? user_id.toString() : '';
        const living = window.YCLiveUtils.safeGet(liveStream, 'living', false);
        const viewCountStr = window.YCLiveUtils.safeGet(source, 'currentWatching', '-1');
        const viewCount = window.YCLiveUtils.convertChineseNumber(viewCountStr);

        // 初始化目标对象
        const target = {
            platformId: window.YCLiveUtils.safeGet(liveStream, 'liveStreamId', ''),
            status: living ? 2 : 0,
            title: window.YCLiveUtils.safeGet(liveStream, 'caption', ''),
            viewCount: living ? viewCount : '-1',
            likeCount: parseInt(window.YCLiveUtils.safeGet(source, 'counts.fanCount', 0), 10),
            owner: {
                platformId: user_id_str,
                platformSecUid: window.YCLiveUtils.safeGet(liveStream, 'userEid', ''),
                nickname: window.YCLiveUtils.safeGet(user, 'user_name', ''),
                avatar: window.YCLiveUtils.safeGet(user, 'headurl', '')
            },
            anchor: {
                platformId: user_id_str,
                platformSecUid: window.YCLiveUtils.safeGet(liveStream, 'userEid', ''),
                nickname: window.YCLiveUtils.safeGet(user, 'user_name', ''),
                avatar: window.YCLiveUtils.safeGet(user, 'headurl', '')
            },
            qrcodeUrl: window.YCLiveUtils.safeGet(liveStream, 'coverUrl', ''),
            streamUrl: { flvPullUrl: {}, hlsPullUrlMap: {}, hlsPullUrl: '', defaultResolution: '' },
            webStreamUrl: { flvPullUrl: {}, hlsPullUrlMap: {}, hlsPullUrl: '', defaultResolution: '' }
        };

        // 处理 liveAdaptiveManifest
        let liveAdaptiveManifest = window.YCLiveUtils.safeGet(liveStream, 'liveAdaptiveManifest', []);
        if (Array.isArray(liveAdaptiveManifest) && liveAdaptiveManifest.length > 0) {
            const representations = liveAdaptiveManifest[0].adaptationSet.representation || [];
            liveAdaptiveManifest[0].adaptationSet.representation = window.YCLiveUtils.sortByBitrate(representations);
        }

        // 分配 FLV URLs
        ['FULL_HD1', 'HD1', 'SD1', 'SD2'].forEach((resolution, i) => {
            const representations = liveAdaptiveManifest[0]?.adaptationSet?.representation || [];
            target.streamUrl.flvPullUrl[resolution] = window.YCLiveUtils.extractUrlFromRepresentation(representations, i);
        });

        // 处理 multiResolutionHlsPlayUrls 和 multiResolutionPlayUrls
        let multiResolutionHlsPlayUrls = window.YCLiveUtils.sortByLevel(YCLiveUtils.safeGet(liveStream, 'multiResolutionHlsPlayUrls', []));
        let multiResolutionPlayUrls = window.YCLiveUtils.sortByLevel(YCLiveUtils.safeGet(liveStream, 'multiResolutionPlayUrls', []));

        ['FULL_HD1', 'HD1', 'SD1', 'SD2'].forEach((resolution, i) => {
            if (multiResolutionHlsPlayUrls[i]?.urls?.[0]?.url) {
                target.streamUrl.hlsPullUrlMap[resolution] = multiResolutionHlsPlayUrls[i].urls[0].url;
                target.webStreamUrl.hlsPullUrlMap[resolution] = multiResolutionHlsPlayUrls[i].urls[0].url;
            }
            if (multiResolutionPlayUrls[i]?.urls?.[0]?.url) {
                target.webStreamUrl.flvPullUrl[resolution] = multiResolutionPlayUrls[i].urls[0].url;
            }
        });

        target.streamUrl.hlsPullUrl = window.YCLiveUtils.safeGet(liveStream, 'hlsPlayUrl', '');
        target.webStreamUrl.hlsPullUrl = target.streamUrl.hlsPullUrl;

        return target;
    };

    window.YCLiveUtils.findLiveStreamObjects = function (obj) {
        let queue = [obj];

        while (queue.length > 0) {
            let currentObj = queue.shift();

            // 检查当前对象是否具有 liveStream 属性且 liveStream 是一个对象
            if (currentObj.hasOwnProperty('liveStream') && typeof currentObj.liveStream === 'object') {
                return currentObj;
            } else {
                // 将当前对象的所有子对象加入队列中
                for (let key in currentObj) {
                    if (currentObj.hasOwnProperty(key)) { // 只处理对象自身的属性
                        let value = currentObj[key];
                        if (typeof value === 'object' && value !== null) {
                            queue.push(value);
                        }
                    }
                }
            }
        }

        return null;
    };

    window.YCLiveUtils.checkCaptcha = function() {
        // 获取文档中所有的 iframe
        let iframes = document.querySelectorAll('iframe');
        let targetIframe = null;
        // 遍历所有 iframe，查找 src 包含 'captcha' 的 iframe
        iframes.forEach(iframe => {
            if (iframe.src && iframe.src.includes('captcha')) {
                targetIframe = iframe;
                return false; // 找到后退出循环
            }
        });
        if (targetIframe) {
            // 获取 iframe 的文档对象，兼容性处理
            let iframeDocument = targetIframe.contentDocument || targetIframe.contentWindow.document;
            let element = iframeDocument.querySelector('.kwai-captcha-slider-wrapper.kwai-captcha-page');
            if (element) {
                return true;
            }
        }
        return false;
    };

    // 获取在线观众数量
    window.YCLiveUtils.setLiveStatus = function () {
        // 获取元素
        let play = document.querySelector('.video-poster-play');
        if (play) {
            // 创建一个新的鼠标事件
            let clickEvent = new MouseEvent('click', {
                view: window,
                bubbles: true,
                cancelable: true
            });
            // 分发事件
            play.dispatchEvent(clickEvent);
        } else {
            let target = document.querySelector('.author-info-view__count');
            if (target && target.textContent) {
                window.YCApp.invokeMethod(MethodNames.setLiveStatus, target.textContent);
            } else {
                window.YCApp.invokeMethod(MethodNames.setLiveStatus, '-1');
            }
        }
    };

    window.YCLiveUtils.getLiveInfo = function (streamObj) {
        try {
            let roomInfo = window.YCLiveUtils.transformSourceToTarget(streamObj);
            if (roomInfo)
                window.YCApp.invokeMethod(MethodNames.setLiveInfo, JSON.stringify(roomInfo));
            else
                window.YCApp.invokeMethod(MethodNames.setLiveInfo, '');
        } catch (e) {
            window.YCApp.invokeMethod(MethodNames.setLiveInfo, '');
        }

        // 安装状态定时器
        if (interval > 0 && typeof window.qt !== 'undefined' && typeof window.YCApp !== 'undefined') {
            setInterval(window.YCLiveUtils.setLiveStatus, interval);
        }
    };

    // 检查 INIT_STATE 是否已经存在且有效
    window.YCLiveUtils.checkInitState = function () {
        if (window.YCLiveUtils.checkCaptcha()) {
            console.log("JS: checked captcha.");
            clearInterval(window.YCLiveUtils.intervalId);
            window.YCApp.invokeMethod(MethodNames.setCaptcha, '1');
            return;
        }
        if (typeof window.INIT_STATE !== 'undefined' && window.INIT_STATE !== null) {
            let streamObj = window.YCLiveUtils.findLiveStreamObjects(window.INIT_STATE);
            if (streamObj) {
                console.log("JS: found live stream.");
                // 如果 INIT_STATE 有效，则清除定时器，停止监测
                clearInterval(window.YCLiveUtils.intervalId);
                window.YCLiveUtils.getLiveInfo(streamObj);
            } else {
                console.log("JS: not found live stream and will reload.");
                clearInterval(window.YCLiveUtils.intervalId);
                // 6秒后重新加载
                setTimeout(() => {                    
                    window.location.reload();
                }, 6000);
            }
        }
    };

    // 设置定时器，每秒（1000毫秒）检查一次 INIT_STATE
    window.YCLiveUtils.intervalId = setInterval(window.YCLiveUtils.checkInitState, 6000);

    // 可选：如果需要立即检查一次，可以在设置定时器后立即调用一次 checkInitState 函数
    window.YCLiveUtils.checkInitState();
})('%1',%2);)" } };
    }
};

#endif // KUAISHOU_H
